package org.example.marker.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.api.marker.controller.UidControllerFeign;
import org.example.marker.config.AppConfig;
import org.example.marker.service.UidGeneratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;


@Slf4j
@RestController
@RequestMapping(value = "/uid")
public class UidController implements UidControllerFeign {

    @Autowired
    private AppConfig appConfig;

    @Autowired
    @Qualifier("defaultUidGeneratorService")
    private UidGeneratorService defaultUidGeneratorService;

    @GetMapping
    public Long getUid(@RequestParam(name = "appId", required = false, defaultValue = "0") long appId) {
        return this.defaultUidGeneratorService.getUID(appId);
    }

    @GetMapping("/batch")
    @Override
    public List<Long> batchGetUid(@RequestParam(name = "appId", required = false, defaultValue = "0") long appId,
                                  @RequestParam("size") int size) throws Exception {
        log.info(">>> request batch get default uid for appId [{}] size [{}]", appId, size);
        if (this.appConfig.getMaxBatchSize() < size) {
            throw new Exception(String.format("Exceed batch maxSize limit [%s]", this.appConfig.getMaxBatchSize()));
        }
        return IntStream.range(0, size).mapToObj(i -> this.defaultUidGeneratorService.getUID(appId)).collect(Collectors.toList());
    }

    @GetMapping(value = "/parse")
    @Override
    public String parse(@RequestParam("uid") long uid) {
        log.info(">>> request parse uid [{}]", uid);
        return this.defaultUidGeneratorService.parseUID(uid);
    }
}
